package com.itheima;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 文档的搜索
 * @作者 itcast
 * @创建日期 2020/11/3 9:00
 **/
public class EsDemo03 {
    RestHighLevelClient client;
    @Test
    public void page(){
        SearchSourceBuilder builder = new SearchSourceBuilder();
        int page = 2;
        int pageSize = 3;

        builder.from((page - 1) * pageSize);
        builder.size(pageSize);
        // 字段的名称     排序: 升序 降序
        builder.sort("age",SortOrder.DESC);
        printResult(builder);
    }
    /**
     * 排序
     */
    @Test
    public void sort(){
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 字段的名称     排序: 升序 降序
        builder.sort("age",SortOrder.DESC);
        builder.sort("gender",SortOrder.ASC);
        printResult(builder);
    }



    @Test
    public void bool(){
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 创建布尔条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("note","同学")); // note中 必须  分词查询     :  同学
        boolQueryBuilder.filter(QueryBuilders.termQuery("gender","0"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").gte(18));
        builder.query(boolQueryBuilder);
        printResult(builder);
    }

    @Test
    public void range(){
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //构建分词条件  note: 唱歌javaee
        builder.query(QueryBuilders.rangeQuery("age").gte(18).lte(25));
        printResult(builder);
    }
    @Test
    public void term(){
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //构建分词条件  note: 唱歌javaee
        builder.query(QueryBuilders.termQuery("gender","0"));
        printResult(builder);
    }

    @Test
    public void match(){
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //构建分词条件  note: 唱歌javaee
        builder.query(QueryBuilders.matchQuery("note","唱歌javaee"));
        printResult(builder);
    }


    @Test
    public void matchAll() throws IOException {
        List<User> userList = new ArrayList<User>();
//        1. 创建SearchRequest 搜索请求
        SearchRequest request = new SearchRequest("user");
//        SearchSourceBuilder 构建所有请求参数
        SearchSourceBuilder builder = new SearchSourceBuilder();
//        query方法   查询条件
        //        QueryBuilders 快速构建查询条件的
        builder.query(QueryBuilders.matchAllQuery());
//        sort       排序条件
//        from       分页
//        size
//        highlight  高亮1
//        aggregations  聚合条件
//        request.source(builder对象)
//        2. 调用client执行search请求
        request.source(builder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
//        3. 解析响应结果 SearchResponse
//        searchResponse.getHits 得到文档查询总结果
        SearchHits hits = searchResponse.getHits();
//		     .getTotalHits
//                .value 得到总数量
        System.out.println("查询到文档的总记录数: " + hits.getTotalHits().value);
//		     .getHits 得到文档列表
        SearchHit[] docList = hits.getHits();
//        遍历文档列表
        for (SearchHit searchHit : docList) {
            // 文档的json内容
            String userJson = searchHit.getSourceAsString();

            User user = JSON.parseObject(userJson, User.class);

            userList.add(user);

        }
//                .getSource  获取文档的内容
//		     			.getHighliter 获取高亮的相关信息
//        searchResponse.getAggregations 得到聚合结果
        System.out.println(userList);
    }
    public void printResult(SearchSourceBuilder builder){
        List<User> userList = new ArrayList<User>();
//        1. 创建SearchRequest 搜索请求
        SearchRequest request = new SearchRequest("user");
//        SearchSourceBuilder 构建所有请求参数
        request.source(builder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(request, RequestOptions.DEFAULT);
            //        3. 解析响应结果 SearchResponse
//        searchResponse.getHits 得到文档查询总结果
            SearchHits hits = searchResponse.getHits();
//		     .getTotalHits
//                .value 得到总数量
            System.out.println("查询到文档的总记录数: " + hits.getTotalHits().value);
//		     .getHits 得到文档列表
            SearchHit[] docList = hits.getHits();
//        遍历文档列表
            for (SearchHit searchHit : docList) {
                // 文档的json内容
                String userJson = searchHit.getSourceAsString();
                User user = JSON.parseObject(userJson, User.class);
                System.out.println(user);
                userList.add(user);

            }
//                .getSource  获取文档的内容
//		     			.getHighliter 获取高亮的相关信息
//        searchResponse.getAggregations 得到聚合结果
        } catch (IOException e) {
            e.printStackTrace();
        }
    }








    @Before
    public void init(){
        // 构建ES的客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost",9200,"http")
                )
        );
    }
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
